import java.util.HashMap;

/**
* @description: 1224. 最大相等频率
* @author hewei
* @date 2022/8/18 16:46
* @version 1.0
*/

public class MaxEqualFreq {

    public static void main(String[] args) {
        MaxEqualFreq maxEqualFreq = new MaxEqualFreq();
        int[] nums = {2,2,1,1,5,3,3,5};
        System.out.println(maxEqualFreq.maxEqualFreq(nums));
    }

    public int maxEqualFreq(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        HashMap<Integer, Integer> count = new HashMap<>();
        int ans = 0;
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            int temp = nums[i];
            if (!map.containsKey(temp)) {
                count.put(1, count.getOrDefault(1, 0) + 1);
                max = Math.max(max, 1);
                map.put(temp, 1);
            } else {
                Integer integer = map.get(temp);
                map.put(temp, integer + 1);
                count.put(integer, count.get(integer) - 1);
                count.put(integer + 1, count.getOrDefault(integer + 1, 0) + 1);
                max = Math.max(max, integer + 1);
            }
            if (max == 1
                    || count.get(max) == 1 && count.get(max) * max + count.get(max - 1) * (max - 1) == i + 1
                    || count.get(max) * max == i) ans = i + 1;
        }
        return ans;
    }
}
